

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import exception.NBPConnectionException;

public class NBPService {

	private static final String nbpUrlPrefix = "http://www.nbp.pl/kursy/xml/";

	public static URL request(Date date) {
		try {
			
			URL nbpdir = new URL(nbpUrlPrefix + "dir.txt");
	        URLConnection yc = nbpdir.openConnection();
	        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
	        String inputLine;

	        while ((inputLine = in.readLine()) != null) {
	        	if (inputLine.length() > 0 && isTableA(inputLine) && isTableOfDate(inputLine, date)) {
	        		String xmlName = nbpUrlPrefix + inputLine + ".xml";
	        		return new URL(xmlName);
	        	}
	        }
		} catch (Exception ex) {
			throw new NBPConnectionException();
		}
		
		return null;
	}
	
	public static List<URL> request(Date date1, Date date2) {
		
		Date from, to;
		if (date1.before(date2)) {
			from = date1;
			to = date2;
		} else {
			from = date2;
			to = date1;
		}
		
		Calendar start = Calendar.getInstance();
		start.setTime(from);
		
		Calendar end = Calendar.getInstance();
		end.setTime(to);
		
		List<URL> retList = new ArrayList<URL>();
		
		try {
			while (!start.after(end)) {
				Date date = start.getTime();
				
				URL nbpdir = new URL(nbpUrlPrefix + "dir.txt");
		        URLConnection yc = nbpdir.openConnection();
		        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
		        String inputLine;
	
		        while ((inputLine = in.readLine()) != null) {
		        	if (inputLine.length() > 0 && isTableA(inputLine) && isTableOfDate(inputLine, date)) {
		        		String xmlName = nbpUrlPrefix + inputLine + ".xml";
		        		retList.add(new URL(xmlName));
		        	}
		        }
				
				start.add(Calendar.DATE, 1);
			}
		} catch (Exception ex) {
			throw new NBPConnectionException();
		}
		
		return retList;
	}
	
	private static boolean isTableA(String inputLine) {
		return inputLine.charAt(0) == 'a';
	}
	
	private static boolean isTableOfDate(String inputLine, Date date) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		
		String strDate = String.format("%02d%02d%02d", year%100, month+1, day);
		
		return strDate.equals(inputLine.substring(5, 11));
	}

}
